﻿#include "SendMsgWorker.h"

SendMsgWorker::SendMsgWorker(QVector<QByteArray> &dataVec, QSerialPort &serialPort, QObject *parent)
	: QObject(parent), m_dataVec(dataVec), m_serialPort(serialPort)
{
	initCycleWork();
}

void SendMsgWorker::sendInitData()
{
	while (!m_dataVec.isEmpty()) {
		QByteArray sendData = m_dataVec.takeFirst();
		m_serialPort.write(sendData);
		m_serialPort.flush();
		this->thread()->msleep(1000);
		// You might need to wait for write operation completion here
	}

	emit startCycleTimer();
	//m_timer->start(4000);
	//emit finished();
}

void SendMsgWorker::cycleWork()
{
	sendReadBatteryInfoByteArray();
	this->thread()->msleep(1000);
	sendReadBatteryDetailInfoByteArray();
}

void SendMsgWorker::initCycleWork()
{
	m_timer = new QTimer();
	connect(m_timer, &QTimer::timeout, this, &SendMsgWorker::cycleWork);
}

void SendMsgWorker::sendReadBatteryInfoByteArray()
{
	QByteArray sendByteInfo;
	//sendByteInfo.append(static_cast<char>(0x01));
	sendByteInfo.append(CoreData::_nowStationAddress);
	sendByteInfo.append(static_cast<char>(0x03));
	sendByteInfo.append(static_cast<char>(0x10));
	sendByteInfo.append(static_cast<char>(0x00));
	sendByteInfo.append(static_cast<char>(0x00));
	sendByteInfo.append(static_cast<char>(0x19));
	quint16 crc16 = calculateCRC16(sendByteInfo);
	sendByteInfo.append(static_cast<char>(crc16 & 0xFF));
	sendByteInfo.append(static_cast<char>((crc16 >> 8) & 0xFF));

	emit updateLastSendArr(sendByteInfo);
	m_serialPort.write(sendByteInfo);
	m_serialPort.flush();
}

void SendMsgWorker::sendReadBatteryDetailInfoByteArray()
{
	QByteArray sendByteInfo;
	//sendByteInfo.append(static_cast<char>(0x01));
	sendByteInfo.append(CoreData::_nowStationAddress);
	sendByteInfo.append(static_cast<char>(0x03));
	sendByteInfo.append(static_cast<char>(0x11));
	sendByteInfo.append(static_cast<char>(0x01));
	sendByteInfo.append(static_cast<char>(0x02));
	sendByteInfo.append(static_cast<char>(0x58));
	quint16 crc16 = calculateCRC16(sendByteInfo);
	sendByteInfo.append(static_cast<char>(crc16 & 0xFF));
	sendByteInfo.append(static_cast<char>((crc16 >> 8) & 0xFF));

	emit updateLastSendArr(sendByteInfo);
	m_serialPort.write(sendByteInfo);
	m_serialPort.flush();
}

SendMsgWorker::~SendMsgWorker()
{
	delete m_timer;
}

quint16 SendMsgWorker::calculateCRC16(const QByteArray &data)
{
	quint16 crc = 0xFFFF;
	QDataStream stream(data);
	while (!stream.atEnd()) {
		quint8 byte;
		stream >> byte;
		crc ^= (quint16)byte;
		for (int i = 0; i < 8; ++i) {
			if (crc & 0x0001) {
				crc >>= 1;
				crc ^= 0xA001;
			}
			else {
				crc >>= 1;
			}
		}
	}
	return crc;
}

void SendMsgWorker::startTimer(unsigned long time)
{
	m_timer->start(time);
}
